﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using produccion.clases;
using System.Data;

namespace produccion.forms
{
    /// <summary>
    /// Lógica de interacción para frmCamMat.xaml
    /// </summary>
    public partial class frmCamMat : Window
    {
        CLSMAEEST MaeEst = new CLSMAEEST();
        CLSMAEMAT MaeMat = new CLSMAEMAT();
        CLSMAEMTP MaeMtp = new CLSMAEMTP();
        CLSMAECOLP MaeColP = new CLSMAECOLP();
        DataTable dtMat = new DataTable();

        public frmCamMat()
        {
            InitializeComponent();
        }

        private void txtMatCam_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (txtMatCam.Text.Length == 10)
            {
                MaeMat.CODMAT_MAT = txtMatCam.Text.Substring(0,6);
                if (MaeMat.ExisteMateria())
                {
                    MaeColP.CODCOL_COL = txtMatCam.Text.Substring(6, 4);
                    if (MaeColP.existe())
                    {
                        Mouse.OverrideCursor = Cursors.Wait;
                        MaeMat.Consultar();                        
                        MaeColP.consultar();
                        txtNomMatCam.Text = MaeMat.NOMMAT_MAT + " " + MaeColP.NOMCOL_COL;
                        MaeMtp.CODMAT_MTP = txtMatCam.Text.Substring(0, 6);
                        MaeMtp.CODCOL_MTP = txtMatCam.Text.Substring(6, 4);
                        if (MaeMtp.existe())
                        {
                            MaeEst.CODMTP_EST = txtMatCam.Text;
                            dtMat = MaeEst.ConsultaMaterial();
                            dtMat.Columns.Add(new DataColumn("CAMBIAR", System.Type.GetType("System.Boolean")));
                            dtMat.Columns["CAMBIAR"].DefaultValue = false;
                            for (int i = 0; i < dtMat.Rows.Count; i++)
                            {
                                dtMat.Rows[i]["CAMBIAR"] = false;
                            }
                            dgMat.ItemsSource = dtMat.DefaultView;
                        }
                        else
                        {
                            MessageBox.Show("No existe la materia prima!", "Cambiar material", MessageBoxButton.OK, MessageBoxImage.Warning);
                            txtMatCam.Text = "";
                            return;
                        }
                        Mouse.OverrideCursor = Cursors.Arrow;
                    }
                    else
                    {
                        MessageBox.Show("No existe el color!", "Cambiar material", MessageBoxButton.OK, MessageBoxImage.Warning);
                        txtMatCam.Text = "";
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("No existe el material!", "Cambiar material", MessageBoxButton.OK, MessageBoxImage.Warning);
                    txtMatCam.Text = "";
                    return;
                }
            }
            else
            {
                LimpiarControles();
            }
        }

        private void LimpiarControles()
        {
            txtNomMatCam.Text = "";
            txtNomMatNue.Text = "";
            txtMatNue.Text = "";
            dtMat.Clear();
            dgMat.ItemsSource = null;
        }

        private void txtMatNue_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (txtMatCam.Text == "")
                return;

            if (txtMatNue.Text.Length == 10)
            {
                MaeMat.CODMAT_MAT = txtMatNue.Text.Substring(0, 6);
                if (MaeMat.ExisteMateria())
                {
                    MaeColP.CODCOL_COL = txtMatNue.Text.Substring(6, 4);
                    if (MaeColP.existe())
                    {
                        MaeMat.Consultar();
                        MaeColP.consultar();
                        txtNomMatNue.Text = MaeMat.NOMMAT_MAT + " " + MaeColP.NOMCOL_COL;
                    }
                }
            }
        }

        private void btnSalir_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void btnGrabar_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtMatCam.Text == "")
                {
                    MessageBox.Show("Ingrese el material a cambiar!", "Material", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return;
                }
                if (txtMatNue.Text == "")
                {
                    MessageBox.Show("Ingrese el material nuevo!", "Material", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return;
                }
                if (MessageBox.Show("Está seguro de realizar los cambios?", "Cambiar materiales en estándar", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    if (txtMatCam.Text == "")
                        return;
                    if (txtMatNue.Text == "")
                        return;
                    if (dtMat.Rows.Count == 0)
                        return;

                    for (int i = 0; i < dtMat.Rows.Count; i++)
                    {
                        if (dtMat.Rows[i][5].Equals(true))
                        {
                            MaeEst.CODREF_EST = dtMat.Rows[i][0].ToString();
                            MaeEst.CODCOL_EST = dtMat.Rows[i][2].ToString();
                            MaeEst.CODTAL_EST = dtMat.Rows[i][3].ToString();
                            MaeEst.CODMTP_EST = txtMatCam.Text;
                            MaeEst.ActualizarMaterialEnRef(txtMatNue.Text);
                        }
                    }
                    txtMatCam.Text = "";
                    LimpiarControles();
                    new MDOgeneral.notificar(wPnot, "Los cambios fueron guardados correctamente.", true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }

        private void btnBuscarMatCam_Click(object sender, RoutedEventArgs e)
        {
            FRMBuscarCol frm = new FRMBuscarCol();
            frm.RequiereColor = true;
            frm.EsReferencia = false;
            frm.ShowDialog();
            if (!String.IsNullOrEmpty(frm.Retorno))
            {
                txtNomMatCam.Text = frm.Retorno.Substring(10);
                txtMatCam.Text = frm.Retorno.Substring(0, 10);
            }
        }

        private void btnbuscarMatNue_Click(object sender, RoutedEventArgs e)
        {
            FRMBuscarCol frm1 = new FRMBuscarCol();
            frm1.RequiereColor = true;
            frm1.EsReferencia = false;
            frm1.ShowDialog();
            if (!String.IsNullOrEmpty(frm1.Retorno))
            {
                txtNomMatNue.Text = frm1.Retorno.Substring(10);
                txtMatNue.Text = frm1.Retorno.Substring(0, 10);
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Keyboard.Focus(txtMatCam);
        }

        private void dgMat_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.Enter && elemento != null)
            {
                e.Handled = true;
                elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }
        }

        //
        // SINGLE CLICK EDITING
        //
        private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DataGridCell cell = sender as DataGridCell;
            if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
            {
                if (!cell.IsFocused)
                {
                    cell.Focus();
                }
                DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
                if (dataGrid != null)
                {
                    if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
                    {
                        if (!cell.IsSelected)
                            cell.IsSelected = true;
                    }
                    else
                    {
                        DataGridRow row = FindVisualParent<DataGridRow>(cell);
                        if (row != null && !row.IsSelected)
                        {
                            row.IsSelected = true;
                        }
                    }
                }
            }
        }

        static T FindVisualParent<T>(UIElement element) where T : UIElement
        {
            UIElement parent = element;
            while (parent != null)
            {
                T correctlyTyped = parent as T;
                if (correctlyTyped != null)
                {
                    return correctlyTyped;
                }

                parent = VisualTreeHelper.GetParent(parent) as UIElement;
            }
            return null;
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.F3 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta == true) { MDOgeneral.logBusquedadAbierta = false; }
            }

            if (e.Key == Key.F4 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta1 == true) { MDOgeneral.logBusquedadAbierta1 = false; }
            }

            if (e.Key == Key.F5 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta2 == true) { MDOgeneral.logBusquedadAbierta2 = false; }
            }
        }
    }
}
